<?php
/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */

define('IN_ADMIN_COMPONENT_CONTROLLER', 'true');

require_once('includes/functions/configuration_functions.php');

class ModuleComponent
{
	function ModuleComponent()
	{
	}

	function action(&$params, $action='query')
	{
		$module_group = prepare_input($params['module_group']);
		if ($module_group == null) $module_group = 'payment';
		$params['module_group'] = $module_group;
		$module_directory = DIR_FS_CATALOG_MODULES . $module_group . '/';
		$module_key = 'MODULE_' . strtoupper($module_group) . '_INSTALLED';

		$PHP_SELF = $_SERVER['PHP_SELF'];
		$file_extension = substr($PHP_SELF, strrpos($PHP_SELF, '.'));

		$params['module_directory'] = $module_directory;
		$params['module_key'] = $module_key;
		$params['file_extension'] = $file_extension;

		$this->module = null;
		$module_class = prepare_input($params['module_class']);
		if ($module_class != null && strlen($module_class) > 0)
		{
			$file = $module_class . $file_extension;
			include_once($module_directory . $file);
			$this->module = new $module_class;
		}

		if ($action == 'Update') 
			return $this->edit($params);
		else if ($action == 'Install')
			return $this->install($params);
		else if ($action == 'Remove')
			return $this->remove($params);
		else 
			return $this->query($params);
	}

	function query(&$params)
	{
		$handle = get_class($this);
		$module_group = $params['module_group'];
		$module_directory = $params['module_directory'];
		$module_key = $params['module_key'];

		$directory_array = array();
		if ($dir = @dir($module_directory)) {
			while ($file = $dir->read()) {
				if (!is_dir($module_directory . $file)) {
					if (substr($file, strrpos($file, '.')) == $params['file_extension']) {
						$directory_array[] = $file;
					}
				}
			}
			sort($directory_array);
			$dir->close();
		}

		$installed_modules_sorted = array();
		$installed_modules_unsorted = array();	
		$modules_sorted = array();
		$modules_unsorted = array();	
		for ($i=0, $n=sizeof($directory_array); $i<$n; $i++)
		{
			$file = $directory_array[$i];
			include_once($module_directory . $file);
			$class = substr($file, 0, strrpos($file, '.'));
			$module = new $class;
			$installed = false;

			if ($module->check() > 0) {
				$installed = true;
				//Do this instead of getting off module to make sure its correct.
				$sort_order = $this->get_sort_order($module->module_key);
				if ($sort_order > 0 && $installed_modules_sorted[$sort_order] == null) {
					$installed_modules_sorted[$sort_order] = $file;
					$modules_sorted[$sort_order] = $file;
				}
				else {
					$installed_modules_unsorted[] = $file;
					$modules_unsorted[] = $file;
				}
			}
			else {
				$modules_unsorted[] = $file;
			}
		}
		ksort($installed_modules_sorted);
		ksort($modules_sorted);
		$installed_modules = array_merge($installed_modules_sorted, $installed_modules_unsorted);
		$all_modules = array_merge($modules_unsorted, $modules_sorted);
		$this->confirm_installed($module_group,$installed_modules);

		for ($i=0, $n=sizeof($all_modules); $i<$n; $i++)
		{
			$file = $all_modules[$i];
			include_once($module_directory . $file);
			$class = substr($file, 0, strrpos($file, '.'));
			$module = new $class;
			$installed=false;
			if ($module->check() > 0) $installed = true;
			
			$value{$handle}{$i}{'group'}= $module_group;
			$value{$handle}{$i}{'class'}= $class;
			$value{$handle}{$i}{'code'}= $module->code;
			$value{$handle}{$i}{'installed'}= $installed;

			$module_key = addcslashes($module->module_key,'%_');
			$sqlQuery = 'select configuration_id, configuration_title, configuration_key, configuration_value, configuration_description, ' . 
			'configuration_format, configuration_values, ' .
			"DATE_FORMAT(date_added, '%Y-%m-%d %H:%i:%s') as date_added, " .
			"DATE_FORMAT(last_modified, '%Y-%m-%d %H:%i:%s') as last_modified " .
			'from ' . TABLE_CONFIGURATION . ' ' .
			'where configuration_key like \'' . $module_key . '\_%\' ' .
			'order by sort_order';
			$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
			$j=0;
			while($row = mysql_fetch_array($dataReturned))
			{
				$value{$handle}{$i}{'configurations'}{$j}{'id'}=(int)$row['configuration_id'];
				$value{$handle}{$i}{'configurations'}{$j}{'title'}= $row['configuration_title'];
				$value{$handle}{$i}{'configurations'}{$j}{'key'}= $row['configuration_key'];
				$value{$handle}{$i}{'configurations'}{$j}{'description'}= $row['configuration_description'];
				$value{$handle}{$i}{'configurations'}{$j}{'value'}= $row['configuration_value'];
				$value{$handle}{$i}{'configurations'}{$j}{'format'}= $row['configuration_format'];
				$configuration_values = $row['configuration_values'];
				$value{$handle}{$i}{'configurations'}{$j}{'date_added'}= $row['date_added'];
				$value{$handle}{$i}{'configurations'}{$j}{'last_modified'}= $row['last_modified'];

				$values = array();
				if ($configuration_values != null && $configuration_values != 'NULL' && strlen(trim($configuration_values)) > 0) {
					$pos = strpos($configuration_values, ',');
					if ($pos === false) {
						eval('$values = ' . $configuration_values . ';');
					}
					else {
						$values_untrimmed = explode(',', $configuration_values);
						reset($values_untrimmed);
						$valueIndex = 0;
						while (list(, $value_untrimmed) = each($values_untrimmed)) 
						{
							$value_trimmed = trim($value_untrimmed);
							$values[$valueIndex]['value'] = $value_trimmed;
							$values[$valueIndex]['title'] = $value_trimmed;
							$valueIndex++;
						}
					}
				}
				$value{$handle}{$i}{'configurations'}{$j}{'values'}= $values;
				$j++;
			}
		}
		return $value;
	}

	function install(&$params)
	{
		$this->module->install();

		return $this->query($params);
	}

	function remove(&$params)
	{
		$this->module->remove();

		return $this->query($params);
	}

	function edit(&$params)
	{
		$module_key = addcslashes($this->module->module_key,'%_');

		$sqlQuery = 'select configuration_key ' .
		'from ' . TABLE_CONFIGURATION . ' ' .
		'where configuration_key like \'' . $module_key . '\_%\' ' .
		'order by sort_order';
		$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
		$i = 0;
		while($row = mysql_fetch_array($dataReturned))
		{
			$key = $row['configuration_key'];

			if (isset($params[$key])) {
				$sql = 'update ' . TABLE_CONFIGURATION . ' ' .
				'set configuration_value = \'' . mysql_real_escape_string($params[$key]) . '\', ' .
				'last_modified=now() ' .
				'where configuration_key = \'' . $key . '\'';
				mysql_query($sql) or die(mysql_error());
			}
		}

		return $this->query($params);
	}

	function confirm_installed(&$module_group,&$installed_modules)
	{
		$imploded_installed_modules = implode(';', $installed_modules);
		$module_key = '\'MODULE_' . strtoupper($module_group) . '_INSTALLED\'';
		$sqlQuery = 'select configuration_value from ' . TABLE_CONFIGURATION . ' where configuration_key = ' . $module_key ;
		$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
		while($row = mysql_fetch_array($dataReturned))
		{
			$configuration_value = $row['configuration_value'];
			break;
		}
		if ($configuration_value != null) 
		{
			if ($configuration_value != $imploded_installed_modules)
			{
				$sql = 'update ' . TABLE_CONFIGURATION . ' set configuration_value = \'' . $imploded_installed_modules . '\', last_modified = now() where configuration_key = ' . $module_key;
				mysql_query($sql) or die(mysql_error());
			}
		}
		else {
			$sql = 'insert into ' . TABLE_CONFIGURATION . ' (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values (\'Installed Modules\', ' . $module_key . ', \'' . $imploded_installed_modules . '\', \'This is automatically updated. No need to edit.\', \'6\', \'0\', now())';
			mysql_query($sql) or die(mysql_error());
		}
	}

	function get_sort_order($module_key)
	{
		$sqlQuery = 'select configuration_value	from ' . TABLE_CONFIGURATION . ' where configuration_key = \'' . $module_key . '_SORT_ORDER\'';
		$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
		while($row = mysql_fetch_array($dataReturned))
		{
			$configuration_value = $row['configuration_value'];
			break;
		}
		return (int)$configuration_value;
	}		
}
?>
